﻿using System;
using Microsoft.VisualStudio.SharePoint;
using Microsoft.VisualStudio.SharePoint.Explorer;
using CodeCounsel.SharePoint.DevTools.Commands;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.SharePoint.Explorer.Extensions;
using System.Windows.Forms;

namespace CodeCounsel.SharePoint.DevTools.ExplorerNodeExtensions
{
    [Export(typeof(IExplorerNodeTypeProvider)),
    ExplorerNodeType(NodeIDs.WebPartNode)]
    public class WebPartNodeTypeProvider
        : IExplorerNodeTypeProvider
    {
        internal static void CreateWebPartNodes(IExplorerNode parentNode)
        {
            ItemInfo[] webParts = parentNode.Context.SharePointConnection.ExecuteCommand<ItemInfo[]>(CommandIDs.GetWebParts);
            foreach (ItemInfo webPart in webParts)
            {
                CreateNode(parentNode, webPart);
            }
        }

        internal static IExplorerNode CreateNode(IExplorerNode parentNode, ItemInfo webPart)
        {
            Dictionary<object, object> annotations = new Dictionary<object, object>();
            annotations.Add(typeof(ItemInfo), webPart);
            return parentNode.ChildNodes.Add(NodeIDs.WebPartNode, String.IsNullOrEmpty(webPart.Title) == false ? webPart.Title : webPart.Name, annotations);
        }

        public void InitializeType(IExplorerNodeTypeDefinition typeDefinition)
        {
            typeDefinition.IsAlwaysLeaf = true;
            typeDefinition.NodePropertiesRequested += NodePropertiesRequested;
            typeDefinition.NodeMenuItemsRequested += NodeMenuItemsRequested;
        }

        void NodeMenuItemsRequested(object sender, ExplorerNodeMenuItemsRequestedEventArgs e)
        {
            IMenuItem copyWebPartDefinition = e.MenuItems.Add("Copy Definition");
            copyWebPartDefinition.Click +=
                delegate
                {
                    ItemInfo webPartInfo = e.Node.GetAnnotation<ItemInfo>();
                    string webPartDefinition = e.Node.Context.SharePointConnection.ExecuteCommand<ItemInfo, string>(CommandIDs.GetWebPartDefinition, webPartInfo);
                    Clipboard.SetData(DataFormats.Text, webPartDefinition);
                };
        }

        void NodePropertiesRequested(object sender, ExplorerNodePropertiesRequestedEventArgs e)
        {
            ItemInfo webPartInfo = e.Node.GetAnnotation<ItemInfo>();
            Dictionary<string, string> webpartProperties = e.Node.Context.SharePointConnection.ExecuteCommand<ItemInfo, Dictionary<string, string>>(CommandIDs.GetWebPartProperties, webPartInfo);
            object propertySource = e.Node.Context.CreatePropertySourceObject(webpartProperties);
            e.PropertySources.Add(propertySource);
        }
    }
}
